<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院" prop="hospital">
        <el-input
          v-model="queryParams.hospital"
          placeholder="请输入医院"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病例时间" prop="caseTime">
        <el-date-picker clearable
          v-model="queryParams.caseTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择病例时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="病例描述" prop="caseDescription">
        <el-input
          v-model="queryParams.caseDescription"
          placeholder="请输入病例描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:file:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:file:edit']"
        >查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:file:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:file:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="病例用户名称" align="center" prop="caseName" />
      <el-table-column label="病例简介" align="center" prop="title" />
      <el-table-column label="医院" align="center" prop="hospital" />
      <el-table-column label="病例时间" align="center" prop="caseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.caseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="病例描述" align="center" prop="caseDescription" />
      <el-table-column label="创建人名称" align="center" prop="createName" />
      <el-table-column label="更新人名称" align="center" prop="updateName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:file:edit']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改病例档案管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="病例人姓名" prop="caseName">
              <el-input disabled v-model="form.caseName" placeholder="请输入病例人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院" prop="hospital">
              <el-input disabled v-model="form.hospital" placeholder="请输入医院" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="病例描述" prop="caseDescription">
              <el-input disabled v-model="form.title" placeholder="请输入病例描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病例时间" prop="caseTime">
              <el-date-picker clearable
                v-model="form.caseTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择病例时间"
                disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="病例详情" prop="caseDescription">
              <el-input type="textarea" :rows="3" disabled v-model="form.caseDescription" placeholder="请输入病例详情" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="病例图片">
              <div class="attalist">
                <img v-for="(item,index) in form.attachFiles" :key="index" :src="item.url" class="attaimg"/>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="病例文件">
              <el-upload
                ref="upload"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-preview="handlePreview"
                :auto-upload="false"
                :file-list="attafileList"
                disabled
                name="haha"
              >
                <!-- <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/system/file";
import { getToken } from "@/utils/auth";
export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 病例档案管理表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospital: null,
        caseTime: null,
        caseDescription: null,
        createName: null,
        updateName: null,
        orderByColumn:'createTime',
        isAsc:'DESC'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      attafileList:[]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询病例档案管理列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hospital: null,
        caseTime: null,
        caseDescription: null,
        createBy: null,
        createName: null,
        createTime: null,
        updateBy: null,
        updateName: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加病例档案管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.attafileList = []
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data;
        if(null != this.form && null != this.form.attachFiles){
          this.attafileList = this.form.attachFiles.filter(file => file.fileClass == '02').map(file => ({
              ...file,          // 保留其他字段
              name: file.fileName, // 将 fileName 改为 name
              fileName: undefined // 删除原来的 fileName 字段
          }));
          this.form.attachFiles = this.form.attachFiles.filter(file => file.fileClass == '01')
        }
        this.open = true;
        this.title = "修改病例档案管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.open = false;

      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.id != null) {
      //       updateFile(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addFile(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除病例档案管理编号为"' + ids + '"的数据项？').then(function() {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    handlePreview(file){
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.target = "_blank";
      a.download = file.name;
      a.href = file.url;//路径前拼上前缀，完整路径
      a.dispatchEvent(event);
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-date-editor{
  width: 100%;
}
::v-deep .el-upload{
  display:none;
}
.attalist{
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .attaimg{
    width: 200px;
    height: 200px;
    margin: 10px 20px 0 0;
  }
}
</style>